<template>
	<ul class="list">
		<li class="item" v-for="key in letters" :key="key" 
		@click="handleLetterClick" 
		@touchstart.prevent="handleTouchStart"
		@touchmove="handleTouchMove"
		@touchend="handleTouchEnd"
		>{{ key }}</li>
	</ul>
</template>

<script>
	export default {
		name: 'Alphabet',
		data() {
			return {
				touchStatus: false,
				startY: 0,
				timer: null,
			};
		},
		updated() { // 当数据更新时且页面渲染完成时
			this.startY = document.querySelector('.list').firstChild.offsetTop;
		},
		computed: {
			letters() {
				let letters = [];
				for(let k in this.cities){
					letters.push(k)
				}
				return letters;
			}
		},
		methods: {
			handleLetterClick(e) {
				this.$emit('change', e.target.innerText)
			},
			handleTouchStart() {
				this.touchStatus = true; // 当开发滑动的时候
			},
			handleTouchMove(e) {
				if(this.touchStatus){
				// 函数节流，不给太频繁操作
				if(this.timer){
					clearTimeout(this.timer)
				}
				this.timer = setTimeout(() => {
					let touchY = e.touches[0].clientY -79;  // 滑动手指到顶部的距离（减去头部）
					let index = Math.floor((touchY - this.startY) / 20); // 可以算出字母的下标是多少了
					if (index >= 0 && index < this.letters.length) {
						this.$emit('change', this.letters[index]);
					}
				},16)
				}
			},
			handleTouchEnd() {
				this.touchStatus = false; // 当滑动结束的时候
			}
		},
		props: ['cities']
	}
</script>

<style lang="less" scoped>
	@import '~styles/varibles.less';
	.list{
		display: flex;
		flex-direction: column;
		justify-content: center;
		position: absolute;
		top: 1.58rem;
		right: 0;
		bottom: 0;
		width: .4rem;
		.item{
			line-height: .4rem;
			text-align: center;
			color: @bgColor;
		}
	}
</style>
